"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { motion } from "framer-motion"
import { 
  ChevronLeft,
  Users, 
  MapPin, 
  Trophy,
  Plus,
  X,
  Upload,
  AlertCircle
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { useAuth } from "@/contexts/auth-context"
import { competitionsApi } from "@/lib/api"

interface Competition {
  id: string
  title: string
  status: string
}

export default function CreateTeamPage() {
  const router = useRouter()
  const { user, isAuthenticated } = useAuth()
  const [isLoading, setIsLoading] = useState(false)
  const [competitions, setCompetitions] = useState<Competition[]>([])
  const [errors, setErrors] = useState<Record<string, string>>({})

  const [formData, setFormData] = useState({
    name: "",
    description: "",
    location: "",
    max_members: 5,
    is_recruiting: true,
    competition_id: "none",
    skills: [] as string[],
    avatar_url: ""
  })

  const [newSkill, setNewSkill] = useState("")

  // 预定义的技能选项
  const predefinedSkills = [
    "React", "Vue", "Angular", "Node.js", "Python", "Java", "C++", "Go",
    "TypeScript", "JavaScript", "HTML/CSS", "PHP", "Ruby", "Swift", "Kotlin",
    "Flutter", "React Native", "Unity", "Unreal Engine", "Blender",
    "Figma", "Photoshop", "UI/UX", "Product Design", "Graphic Design",
    "Machine Learning", "Deep Learning", "Data Science", "AI", "NLP",
    "Computer Vision", "Blockchain", "Web3", "Smart Contracts", "DeFi",
    "DevOps", "Docker", "Kubernetes", "AWS", "Azure", "GCP",
    "PostgreSQL", "MongoDB", "Redis", "MySQL", "Firebase",
    "Git", "Linux", "Cybersecurity", "Testing", "Agile"
  ]

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: "" }))
    }
  }

  const addSkill = (skill: string) => {
    if (skill && !formData.skills.includes(skill)) {
      setFormData(prev => ({
        ...prev,
        skills: [...prev.skills, skill]
      }))
    }
    setNewSkill("")
  }

  const removeSkill = (skillToRemove: string) => {
    setFormData(prev => ({
      ...prev,
      skills: prev.skills.filter(skill => skill !== skillToRemove)
    }))
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}

    if (!formData.name.trim()) {
      newErrors.name = "团队名称不能为空"
    } else if (formData.name.length < 2) {
      newErrors.name = "团队名称至少需要2个字符"
    } else if (formData.name.length > 50) {
      newErrors.name = "团队名称不能超过50个字符"
    }

    if (!formData.description.trim()) {
      newErrors.description = "团队描述不能为空"
    } else if (formData.description.length < 10) {
      newErrors.description = "团队描述至少需要10个字符"
    } else if (formData.description.length > 500) {
      newErrors.description = "团队描述不能超过500个字符"
    }

    if (formData.max_members < 2) {
      newErrors.max_members = "团队最大人数不能少于2人"
    } else if (formData.max_members > 20) {
      newErrors.max_members = "团队最大人数不能超过20人"
    }

    if (formData.skills.length === 0) {
      newErrors.skills = "请至少添加一个技能标签"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!isAuthenticated) {
      router.push("/auth/login")
      return
    }

    if (!validateForm()) {
      return
    }

    try {
      setIsLoading(true)
      // TODO: 实现创建团队的API调用
      // const response = await teamsApi.createTeam(formData)
      console.log("Creating team with data:", formData)
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 创建成功后跳转到团队详情页
      router.push("/teams/1") // 使用模拟的团队ID
    } catch (error) {
      console.error("Failed to create team:", error)
      setErrors({ submit: "创建团队失败，请稍后重试" })
    } finally {
      setIsLoading(false)
    }
  }

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen pt-20 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-white mb-4">请先登录</h1>
          <p className="text-gray-300 mb-6">您需要登录后才能创建团队</p>
          <Button onClick={() => router.push("/auth/login")} className="bg-gradient-to-r from-blue-500 to-purple-500">
            去登录
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8 max-w-4xl">
        {/* 返回按钮 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="mb-6"
        >
          <Button
            variant="ghost"
            onClick={() => router.back()}
            className="text-white hover:text-blue-300"
          >
            <ChevronLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </motion.div>

        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <h1 className="text-3xl font-bold text-white mb-2">创建团队</h1>
          <p className="text-gray-300">组建你的团队，一起参加竞赛</p>
        </motion.div>

        {/* 表单 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <form onSubmit={handleSubmit} className="space-y-8">
            {/* 基本信息 */}
            <Card className="bg-gray-800/50 border-gray-700">
              <CardHeader>
                <CardTitle className="text-white">基本信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* 团队名称 */}
                <div className="space-y-2">
                  <Label htmlFor="name" className="text-white">团队名称 *</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => handleInputChange("name", e.target.value)}
                    placeholder="输入团队名称"
                    className="bg-gray-700 border-gray-600 text-white"
                  />
                  {errors.name && (
                    <p className="text-red-400 text-sm">{errors.name}</p>
                  )}
                </div>

                {/* 团队描述 */}
                <div className="space-y-2">
                  <Label htmlFor="description" className="text-white">团队描述 *</Label>
                  <Textarea
                    id="description"
                    value={formData.description}
                    onChange={(e) => handleInputChange("description", e.target.value)}
                    placeholder="描述你的团队，包括目标、理念和正在寻找的成员类型"
                    rows={4}
                    className="bg-gray-700 border-gray-600 text-white"
                  />
                  <div className="flex justify-between text-sm text-gray-400">
                    <span>{formData.description.length}/500</span>
                    {errors.description && (
                      <span className="text-red-400">{errors.description}</span>
                    )}
                  </div>
                </div>

                {/* 地理位置 */}
                <div className="space-y-2">
                  <Label htmlFor="location" className="text-white">地理位置</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      id="location"
                      value={formData.location}
                      onChange={(e) => handleInputChange("location", e.target.value)}
                      placeholder="例如：北京、上海、远程"
                      className="pl-10 bg-gray-700 border-gray-600 text-white"
                    />
                  </div>
                </div>

                {/* 最大成员数 */}
                <div className="space-y-2">
                  <Label htmlFor="max_members" className="text-white">最大成员数 *</Label>
                  <div className="relative">
                    <Users className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      id="max_members"
                      type="number"
                      min="2"
                      max="20"
                      value={formData.max_members}
                      onChange={(e) => handleInputChange("max_members", parseInt(e.target.value))}
                      className="pl-10 bg-gray-700 border-gray-600 text-white"
                    />
                  </div>
                  {errors.max_members && (
                    <p className="text-red-400 text-sm">{errors.max_members}</p>
                  )}
                </div>

                {/* 是否招募 */}
                <div className="flex items-center justify-between">
                  <div>
                    <Label className="text-white">开放招募</Label>
                    <p className="text-sm text-gray-400">允许其他用户申请加入团队</p>
                  </div>
                  <Switch
                    checked={formData.is_recruiting}
                    onCheckedChange={(checked) => handleInputChange("is_recruiting", checked)}
                  />
                </div>
              </CardContent>
            </Card>

            {/* 竞赛信息 */}
            <Card className="bg-gray-800/50 border-gray-700">
              <CardHeader>
                <CardTitle className="text-white">竞赛信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="competition" className="text-white">目标竞赛</Label>
                  <div className="relative">
                    <Trophy className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Select value={formData.competition_id} onValueChange={(value) => handleInputChange("competition_id", value)}>
                      <SelectTrigger className="pl-10 bg-gray-700 border-gray-600 text-white">
                        <SelectValue placeholder="选择要参加的竞赛（可选）" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">不指定竞赛</SelectItem>
                        <SelectItem value="1">2024 AI创新大赛</SelectItem>
                        <SelectItem value="2">移动应用创新挑战赛</SelectItem>
                        <SelectItem value="3">Web开发马拉松</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <p className="text-sm text-gray-400">选择团队要参加的竞赛，也可以稍后设置</p>
                </div>
              </CardContent>
            </Card>

            {/* 技能标签 */}
            <Card className="bg-gray-800/50 border-gray-700">
              <CardHeader>
                <CardTitle className="text-white">技能标签 *</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* 当前技能 */}
                {formData.skills.length > 0 && (
                  <div>
                    <Label className="text-white mb-2 block">已添加的技能</Label>
                    <div className="flex flex-wrap gap-2">
                      {formData.skills.map((skill) => (
                        <Badge
                          key={skill}
                          variant="secondary"
                          className="bg-blue-500/20 text-blue-300 pr-1"
                        >
                          {skill}
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeSkill(skill)}
                            className="ml-1 h-auto p-0 text-blue-300 hover:text-red-400"
                          >
                            <X className="w-3 h-3" />
                          </Button>
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}

                {/* 添加技能 */}
                <div className="space-y-2">
                  <Label className="text-white">添加技能</Label>
                  <div className="flex gap-2">
                    <Input
                      value={newSkill}
                      onChange={(e) => setNewSkill(e.target.value)}
                      placeholder="输入技能名称"
                      className="bg-gray-700 border-gray-600 text-white"
                      onKeyPress={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault()
                          addSkill(newSkill)
                        }
                      }}
                    />
                    <Button
                      type="button"
                      onClick={() => addSkill(newSkill)}
                      variant="outline"
                      className="border-gray-600 text-white hover:bg-gray-700"
                    >
                      <Plus className="w-4 h-4" />
                    </Button>
                  </div>
                </div>

                {/* 预定义技能 */}
                <div>
                  <Label className="text-white mb-2 block">常用技能（点击添加）</Label>
                  <div className="flex flex-wrap gap-2 max-h-32 overflow-y-auto">
                    {predefinedSkills
                      .filter(skill => !formData.skills.includes(skill))
                      .map((skill) => (
                        <Badge
                          key={skill}
                          variant="outline"
                          className="cursor-pointer border-gray-600 text-gray-300 hover:bg-gray-700 hover:text-white"
                          onClick={() => addSkill(skill)}
                        >
                          {skill}
                        </Badge>
                      ))}
                  </div>
                </div>

                {errors.skills && (
                  <p className="text-red-400 text-sm">{errors.skills}</p>
                )}
              </CardContent>
            </Card>

            {/* 错误提示 */}
            {errors.submit && (
              <Alert className="border-red-500 bg-red-500/10">
                <AlertCircle className="h-4 w-4 text-red-400" />
                <AlertDescription className="text-red-400">
                  {errors.submit}
                </AlertDescription>
              </Alert>
            )}

            {/* 提交按钮 */}
            <div className="flex gap-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
                className="flex-1 border-gray-600 text-white hover:bg-gray-700"
              >
                取消
              </Button>
              <Button
                type="submit"
                disabled={isLoading}
                className="flex-1 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
              >
                {isLoading ? "创建中..." : "创建团队"}
              </Button>
            </div>
          </form>
        </motion.div>
      </div>
    </div>
  )
}